const goalWeight  = [
    { name: "前锋", value: 10 },
    { name: "中场", value: 3 },
    { name: "后卫", value: 0 }
];

const assistsWeight = [
    { name: "前锋", value: 5 },
    { name: "中场", value: 5 },
    { name: "后卫", value: 0 }
];


const goalProbability = [
    { key: 0, value: 0.012 },
    { key: 1, value: 0.014 },
    { key: 2, value: 0.016 },
    { key: 3, value: 0.018 },
    { key: 4, value: 0.02 },
    { key: 5, value: 0.022 },
    { key: 6, value: 0.024 },
    { key: 7, value: 0.026 },
    { key: 8, value: 0.028 },
    { key: 9, value: 0.03 },
    { key: 10, value: 0.032 }
];

const getProbability = function(data) {
    if (data<0) {
        return 0.01;
    }
    if (data>10) {
        return 0.034;
    }
    return goalProbability[data].value;
}

const playContentList = require('./playContent');

/* 确定进球/助攻的球员 type: 1进球 2助攻 */
function determineScorer(players, type = 1) {
    // 根据球员的位置和能力值来确定进球的球员
    let potentialScorers = [];

    potentialScorers = JSON.parse(JSON.stringify(players));
    
    let minScorers = 100; /* 最小能力值-1 */
    /* 格式化能力值 */
    potentialScorers.map((player)=>{
        if(player.playerScore < minScorers){
            minScorers = player.playerScore;
        }
    })
    potentialScorers.map((player)=>{
        let weight = 0;
        switch(player.playerPosition){
            case "前锋":
                weight = type==1?goalWeight[0].value:assistsWeight[0].value;
                break;
            case "中场":
                weight = type==1?goalWeight[1].value:assistsWeight[1].value;
                break;
            case "后卫":
                weight = type==1?goalWeight[2].value:assistsWeight[2].value;
                break;
            default:
                weight = 0;
        }
        player.playerScore = player.playerScore - minScorers + 1 + weight;
    })
    // 根据能力值随机选择一个球员进球
    let totalAbility = 0;
    potentialScorers.forEach(player => {
        totalAbility += player.playerScore;
    });
    
    const randomAbility = Math.random() * totalAbility;
    let cumulativeAbility = 0;
    let scoringPlayer = null;
    for (let i = 0; i < potentialScorers.length; i++) {
        cumulativeAbility += potentialScorers[i].playerScore;
        if (randomAbility <= cumulativeAbility) {
            scoringPlayer = potentialScorers[i];
            break;
        }
    }

    return scoringPlayer;
}

/* 选择最佳球员 */
const getBestPlayer = function(players,dataList) {
    // 根据球员的位置和能力值来确定进球的球员
    let bestPlayerList = [];
    let bestPlayer = null;

    
    bestPlayerList = JSON.parse(JSON.stringify(players));
    for (let i = 0; i < bestPlayerList.length; i++) {
        let cumulativeAbility = 0;
        dataList.map((item)=>{
            if (bestPlayerList[i].playerId == item.scoringPlayer.playerId) {
                if (item.isgoal) {
                    cumulativeAbility+=2;
                }else{
                    cumulativeAbility++;
                }
            }
            if (item.isAssists) {
                if (bestPlayerList[i].playerId == item.assistsPlayer.playerId) {
                    if (item.isgoal) {
                        cumulativeAbility+=2;
                    }else{
                        cumulativeAbility++;
                    }
                }
             }
        })
        if (bestPlayer) {
            if (bestPlayer.cumulativeAbility < cumulativeAbility) {
                bestPlayer = {...bestPlayerList[i],cumulativeAbility}
            }
        }else{
            bestPlayer = {...bestPlayerList[i],cumulativeAbility}
        }
    }
    
    // let minScorers = 100; /* 最小能力值-1 */
    // /* 格式化能力值 */
    // bestPlayerList.map((player)=>{
    //     if(player.playerScore < minScorers){
    //         minScorers = player.playerScore;
    //     }
    // })

    // // 根据能力值随机选择一个球员进球
    // let totalAbility = 0;
    // bestPlayerList.forEach(player => {
    //     totalAbility += player.playerScore;
    // });
    
    // const randomAbility = Math.random() * totalAbility;
    // let cumulativeAbility = 0;
    // for (let i = 0; i < bestPlayerList.length; i++) {
    //     cumulativeAbility += bestPlayerList[i].playerScore;
    //     if (randomAbility <= cumulativeAbility) {
    //         bestPlayer = bestPlayerList[i];
    //         break;
    //     }
    // }

    return bestPlayer;
}

const singePlay = function(homeTeam,guestTeam) {
    let homeTeamExpect = getProbability(homeTeam.attackValue - guestTeam.defenseValue);
    let guestTeamExpect = getProbability(guestTeam.attackValue - homeTeam.defenseValue);
    let homeTeamGoal = 0;
    let guestTeamGoal = 0;
    let homeTeamGoalAttempts = 0;
    let homeTeamKeyPassing = 0;
    let guestTeamGoalAttempts = 0;
    let guestTeamKeyPassing = 0;
    let CompetitionContent = [];
    let possession1 = 0;
    let possession2 = 0;
    
    let dataList = [];
    for (let i = 0; i < 90; i++) {
        if (randomBoolean(homeTeamExpect)) {
            let scoringPlayer = determineScorer(homeTeam.playerList, 1);
            let assistsPlayer = null;
            let isAssists = randomBoolean(0.8);
            if (isAssists) {
                assistsPlayer = determineScorer(homeTeam.playerList,2);
                if (assistsPlayer) {
                    if (assistsPlayer.playerName==scoringPlayer.playerName) {
                        isAssists = false;
                    }
                }else{
                    isAssists = false;
                }
            }
            homeTeamGoal++;
            homeTeamGoalAttempts++;
            dataList.push({
                isgoal: true,
                time: i+1,
                goalTeam: homeTeam.teamName,
                homeTeamGoal: homeTeamGoal,
                guestTeamGoal: guestTeamGoal,
                homeTeam: homeTeam,
                guestTeam: guestTeam,
                scoringPlayer:scoringPlayer,
                isAssists:isAssists,
                assistsPlayer:assistsPlayer
            })
            let content1 = null;
            if (isAssists) {
                homeTeamKeyPassing++;
                content1 = playContentList.contentList[Math.floor(Math.random() * playContentList.contentList.length)];
            }else{
                content1 = playContentList.contentListNoAssists[Math.floor(Math.random() * playContentList.contentListNoAssists.length)];
            }
            
            let content2 = playContentList.goalList[Math.floor(Math.random() * playContentList.goalList.length)];
            content1 = content1.replace("{subject}", `<span style="color: #409EFF;">${scoringPlayer?.playerName}</span>`)
            content1 = content1.replace("{secondary}", `<span style="color: #409EFF;">${assistsPlayer?.playerName}</span>`)
            CompetitionContent.push({
                time: i+1,
                isgoal: true,
                team:"主队",
                content: `${i+1}' ${homeTeam.teamName}进球 ` + content1 + '，' + content2
            })
            // CompetitionContent.push({
            //     time: i+1,
            //     isgoal: true,
            //     content: `${i+1}' ${homeTeam.teamName} 进球 (${scoringPlayer?.playerName || '无'}) 助攻 (${isAssists ? assistsPlayer?.playerName : '无'})`
            // })
        }
        if (randomBoolean(guestTeamExpect)) {
            let scoringPlayer = determineScorer(guestTeam.playerList, 1);
            let assistsPlayer = null;
            let isAssists = randomBoolean(0.8);
            if (isAssists) {
                assistsPlayer = determineScorer(guestTeam.playerList,2);
                if (assistsPlayer) {
                    if (assistsPlayer.playerName==scoringPlayer.playerName) {
                        isAssists = false;
                    }
                }else{
                    isAssists = false;
                }
            }
            guestTeamGoalAttempts++;
            guestTeamGoal++;
            dataList.push({
                isgoal: true,
                time: i+1,
                goalTeam: guestTeam.teamName,
                homeTeamGoal: homeTeamGoal,
                guestTeamGoal: guestTeamGoal,
                homeTeam: homeTeam,
                guestTeam: guestTeam,
                scoringPlayer:scoringPlayer,
                isAssists:isAssists,
                assistsPlayer:assistsPlayer,
            });
            let content1 = null;
            if (isAssists) {
                guestTeamKeyPassing++;
                content1 = playContentList.contentList[Math.floor(Math.random() * playContentList.contentList.length)];
            }else{
                content1 = playContentList.contentListNoAssists[Math.floor(Math.random() * playContentList.contentListNoAssists.length)];
            }
            let content2 = playContentList.goalList[Math.floor(Math.random() * playContentList.goalList.length)];
            content1 = content1.replace("{subject}", `<span style="color: #409EFF;">${scoringPlayer?.playerName}</span>`)
            content1 = content1.replace("{secondary}", `<span style="color: #409EFF;">${assistsPlayer?.playerName}</span>`)
            CompetitionContent.push({
                time: i+1,
                isgoal: true,
                team:"客队",
                content: `${i+1}' ${guestTeam.teamName}进球 ` + content1 + '，' + content2
            })
        }
        if (randomBoolean(0.1)) {
            if (randomBoolean(homeTeam.attackValue/(homeTeam.attackValue + guestTeam.attackValue))) {
                possession1++;
                let scoringPlayer = determineScorer(homeTeam.playerList, 1);
                let assistsPlayer = null;
                let isAssists = randomBoolean(0.8);
                if (isAssists) {
                    assistsPlayer = determineScorer(homeTeam.playerList,2);
                    if (assistsPlayer) {
                        if (assistsPlayer.playerName==scoringPlayer.playerName) {
                            isAssists = false;
                        }
                    }else{
                        isAssists = false;
                    }
                }
                homeTeamGoalAttempts++;
                dataList.push({
                    isgoal: false,
                    time: i+1,
                    goalTeam: homeTeam.teamName,
                    homeTeamGoal: homeTeamGoal,
                    guestTeamGoal: guestTeamGoal,
                    homeTeam: homeTeam,
                    guestTeam: guestTeam,
                    scoringPlayer:scoringPlayer,
                    isAssists:isAssists,
                    assistsPlayer:assistsPlayer
                })
                if (isAssists) {
                    homeTeamKeyPassing++;
                    let content1 = playContentList.contentList[Math.floor(Math.random() * playContentList.contentList.length)];
                    let content2 = playContentList.resList[Math.floor(Math.random() * playContentList.resList.length)];
                    content1 = content1.replace("{subject}", `<span style="color: #409EFF;">${scoringPlayer?.playerName}</span>`)
                    content1 = content1.replace("{secondary}", `<span style="color: #409EFF;">${assistsPlayer?.playerName}</span>`)
                    CompetitionContent.push({
                        time: i+1,
                        isgoal: false,
                        team:"主队",
                        content: `${i+1}' ` + content1 + '，' + content2
                    })
                }else{
                    let content1 = playContentList.contentListNoAssists[Math.floor(Math.random() * playContentList.contentListNoAssists.length)];
                    let content2 = playContentList.resList[Math.floor(Math.random() * playContentList.resList.length)];
                    content1 = content1.replace("{subject}", `<span style="color: #409EFF;">${scoringPlayer?.playerName}</span>`)
                    CompetitionContent.push({
                        time: i+1,
                        isgoal: false,
                        team:"主队",
                        content: `${i+1}' ` + content1 + '，' + content2
                    })
                }
                
            }else{
                possession2++;
                let scoringPlayer = determineScorer(guestTeam.playerList, 1);
                let assistsPlayer = null;
                let isAssists = randomBoolean(0.8);
                if (isAssists) {
                    assistsPlayer = determineScorer(guestTeam.playerList,2);
                    if (assistsPlayer) {
                        if (assistsPlayer.playerName==scoringPlayer.playerName) {
                            isAssists = false;
                        }
                    }else{
                        isAssists = false;
                    }
                }
                guestTeamGoalAttempts++;
                dataList.push({
                    isgoal: false,
                    time: i+1,
                    goalTeam: guestTeam.teamName,
                    homeTeamGoal: homeTeamGoal,
                    guestTeamGoal: guestTeamGoal,
                    homeTeam: homeTeam,
                    guestTeam: guestTeam,
                    scoringPlayer:scoringPlayer,
                    isAssists:isAssists,
                    assistsPlayer:assistsPlayer,
                });
                if (isAssists) {
                    guestTeamKeyPassing++;
                    let content1 = playContentList.contentList[Math.floor(Math.random() * playContentList.contentList.length)];
                    let content2 = playContentList.resList[Math.floor(Math.random() * playContentList.resList.length)];
                    content1 = content1.replace("{subject}", `<span style="color: #409EFF;">${scoringPlayer?.playerName}</span>`)
                    content1 = content1.replace("{secondary}", `<span style="color: #409EFF;">${assistsPlayer?.playerName}</span>`)
                    CompetitionContent.push({
                        time: i+1,
                        isgoal: false,
                        team:"客队",
                        content: `${i+1}' ` + content1 + '，' + content2
                    })
                }else{
                    let content1 = playContentList.contentListNoAssists[Math.floor(Math.random() * playContentList.contentListNoAssists.length)];
                    let content2 = playContentList.resList[Math.floor(Math.random() * playContentList.resList.length)];
                    content1 = content1.replace("{subject}", `<span style="color: #409EFF;">${scoringPlayer?.playerName}</span>`)
                    CompetitionContent.push({
                        time: i+1,
                        isgoal: false,
                        team:"客队",
                        content: `${i+1}' ` + content1 + '，' + content2
                    })
                }
            }
        }else{
            if (randomBoolean(homeTeam.attackValue/(homeTeam.attackValue + guestTeam.attackValue))) {
                possession1++;
            }else{
                possession2++;
            }
        }
        
    }
    let bestPlayer = null
    if (homeTeamGoal > guestTeamGoal) {
        bestPlayer = getBestPlayer(homeTeam.playerList,dataList);
    }else if (homeTeamGoal < guestTeamGoal) {
        bestPlayer = getBestPlayer(guestTeam.playerList,dataList);
    }else{
        if (randomBoolean(0.5)) {
            bestPlayer = getBestPlayer(homeTeam.playerList,dataList);
        }else{
            bestPlayer = getBestPlayer(guestTeam.playerList,dataList);
        }
    }
    return {
        dataList: dataList,
        homeTeamGoal: homeTeamGoal,
        guestTeamGoal: guestTeamGoal,
        homeTeamGoalAttempts:homeTeamGoalAttempts,
        homeTeamKeyPassing:homeTeamKeyPassing,
        guestTeamGoalAttempts:guestTeamGoalAttempts,
        guestTeamKeyPassing:guestTeamKeyPassing,
        homeTeam: homeTeam,
        guestTeam: guestTeam,
        bestPlayer: bestPlayer,
        content:CompetitionContent,
        homeTeamPossession:(possession1*100/90).toFixed(1),
        guestTeamPossession:(possession2*100/90).toFixed(1),
    }
}

function selectItemByProbability(array) {
    // 计算总概率
    const totalProbability = array.reduce((total, item) => total + item.probability, 0);
    
    // 生成随机数
    const randomNum = Math.random() * totalProbability;
    
    // 根据随机数选中元素
    let cumulativeProbability = 0;
    for (const item of array) {
        cumulativeProbability += item.probability;
        if (randomNum <= cumulativeProbability) {
            return item;
        }
    }
    
    // 如果未选中任何元素，返回null
    return null;
}



function randomBoolean(probability) {
    // 随机生成一个 0 到 1 之间的小数
    const randomValue = Math.random();

    // 如果随机值小于等于概率值，则返回 true，否则返回 false
    return randomValue <= probability;
}

/* 赛程安排 */
function generateSchedule(teams) {
    /* let schedule = [];

    for (let round = 1; round <= teams.length * 2 - 2; round++) {
        let roundSchedule = [];
        
        for (let i = 0; i < teams.length / 2; i++) {
            let homeTeam = teams[i];
            let guestTeam = teams[teams.length - 1 - i];
            
            if (homeTeam !== guestTeam) {
                roundSchedule.push({ homeTeam: homeTeam, guestTeam: guestTeam });
            }
        }
        
        schedule.push(roundSchedule);

        // 重新排列球队
        teams.splice(1, 0, teams.pop());
    }

    return schedule; */
    let schedule = [];

    for (let round = 1; round <= teams.length * 2 - 2; round++) {
        let roundSchedule = [];
        
        for (let i = 0; i < teams.length / 2; i++) {
            let homeTeam = teams[i];
            let awayTeam = teams[teams.length - 1 - i];
            
            // 在奇数轮次，交换主客队
            if (round % 2 === 1) {
                let temp = homeTeam;
                homeTeam = awayTeam;
                awayTeam = temp;
            }

            if (homeTeam !== awayTeam) {
                roundSchedule.push({ homeTeam: homeTeam, guestTeam: awayTeam });
            }
        }
        
        schedule.push(roundSchedule);

        // 重新排列球队
        teams.splice(1, 0, teams.pop());
    }

    return schedule;
}

/* 射手榜和助攻榜生成 */
function generateGoalScorers(matchList, players) {
    let goalList = []
    for (let index = 0; index < matchList.length; index++) {
        // let matchGoalList = matchList[index].dataList.map((item)=>{
        //     if (item.isgoal) {
        //         return item
        //     }
        // })
        goalList = [...goalList,...matchList[index].dataList];
    }
    

    goalList.map((item)=>{
        for (let i = 0; i < players.length; i++) {
            if (players[i].playerId == item.scoringPlayer.playerId) {
                players[i].goalAttempts++;
                if (item.isgoal) {
                    players[i].goal++;
                }
            }
            if (item.isAssists) {
                if (players[i].playerId == item.assistsPlayer.playerId) {
                    players[i].keyPassing++
                    if (item.isgoal) {
                        players[i].assists++;
                    }
                }
            }
        }
    })
    matchList.map((item)=>{
        for (let i = 0; i < players.length; i++) {
            if (item.bestPlayer.playerId == players[i].playerId) {
                players[i].mvp++;
            }
        }
    })
    for (let i = 0; i < players.length; i++) {
        players[i].performance = players[i].goal + players[i].assists + (players[i].mvp*3);
    }
    players.sort((a, b) => b.goal - a.goal);
    return players;
}

/* 生成积分榜 */
function generatePointsTable(matchList, teams) {
    matchList.map((item)=>{
        for (let i = 0; i < teams.length; i++) {
            if (item.homeTeam.teamId == teams[i].teamId) {

                teams[i].goal += item.homeTeamGoal;
                teams[i].fumble += item.guestTeamGoal;
                teams[i].goalAttempts += item.homeTeamGoalAttempts;
                teams[i].keyPassing += item.homeTeamKeyPassing;
                teams[i].venue++;
                if (item.homeTeamGoal > item.guestTeamGoal) {
                    teams[i].win++;
                } else if (item.homeTeamGoal < item.guestTeamGoal) {
                    teams[i].lose++;
                } else {
                    teams[i].draw++;
                }
            }
            if (item.guestTeam.teamId == teams[i].teamId) {
                teams[i].fumble += item.homeTeamGoal;
                teams[i].goal += item.guestTeamGoal;
                teams[i].goalAttempts += item.guestTeamGoalAttempts;
                teams[i].keyPassing += item.guestTeamKeyPassing;
                teams[i].venue++;
                if (item.homeTeamGoal < item.guestTeamGoal) {
                    teams[i].win++;
                } else if (item.homeTeamGoal > item.guestTeamGoal) {
                    teams[i].lose++;
                } else {
                    teams[i].draw++;
                }
            }
        }
        
    })
    teams = teams.map((item)=>{
        item.difference = item.goal - item.fumble;
        item.score = item.win * 3 + item.draw;
        return item;
    })
    teams.sort((a, b) => {
        if (a.score !== b.score) {
            return b.score - a.score;
        } else if (a.difference !== b.difference) {
            return b.difference - a.difference;
        } else {
            return b.venue - a.venue;
        }
    })
    return teams;
}


/* // 测试
let teams = ["Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8"];
let schedule = generateSchedule(teams);

// 输出比赛赛程
schedule.forEach(function(round, index) {
    console.log("第 " + (index + 1) + " 轮比赛：");
    round.forEach(function(match) {
        console.log(match.homeTeam + " vs " + match.guestTeam);
    });
    console.log();
}); */


module.exports = {
    singePlay,
    getProbability,
    randomBoolean,
    generateSchedule,
    generateGoalScorers,
    generatePointsTable
}